package org.jeecg.modules.xl.home.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.system.vo.DictModel;
import org.jeecg.modules.xl.aftersale.entity.XlCustomerAftersale;
import org.jeecg.modules.xl.aftersale.service.IXlCustomerAftersaleService;
import org.jeecg.modules.xl.home.mapper.HomeMapper;
import org.jeecg.modules.xl.home.query.HomeQuery;
import org.jeecg.modules.xl.home.service.HomeService;
import org.jeecg.modules.xl.home.vo.*;
import org.jeecg.modules.xl.order.utils.DictUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class HomeServiceImpl implements HomeService {

    @Resource
    private HomeMapper homeMapper;
    @Resource
    private IXlCustomerAftersaleService aftersaleService;
    @Resource
    private DictUtils dictUtils;

    @Override
    public HomeDayDataVO queryDayData() {
        //订单数据
        HomeDayDataVO dayOrder = homeMapper.queryDayOrder();
        if (dayOrder == null){
            return new HomeDayDataVO();
        }
        //发货数据
        HomeDayDataVO dayShipment = homeMapper.queryDayShipment();
        //售后数据
        HomeDayDataVO dayAftersale = homeMapper.queryDayAftersale();

        //赋值对应数据
        if (dayShipment != null){
            dayOrder.setShipmentCnt(dayShipment.getShipmentCnt());
            dayOrder.setUnShipmentCnt(dayShipment.getUnShipmentCnt());
        }
        if (dayAftersale != null){
            dayOrder.setAftersaleCnt(dayAftersale.getAftersaleCnt());
            dayOrder.setUnAftersaleCnt(dayAftersale.getUnAftersaleCnt());
        }
        return dayOrder;
    }

    @Override
    public IPage<HomeStoreListVO> storyRanking(Page page, HomeQuery query) {
        return homeMapper.getStoryList(page,query);
    }

    @Override
    public IPage<HomeProductListVO> productRanking(Page page,HomeQuery query) {
        return homeMapper.getProductList(page,query);
    }

    @Override
    public HomeAftersaleVO aftersaleData(HomeQuery query) {
        //判断 城市和渠道条件是否有  有则拼接
        String existsWhere = "";
        if (StringUtils.isNotBlank(query.getCity())) {
            existsWhere += " and co.city = '"+query.getCity()+"' ";
        }
        if (StringUtils.isNotBlank(query.getCustomerTypeCode())) {
            existsWhere += " and co.customer_type_code = '"+query.getCustomerTypeCode()+"' ";
        }
        //查询条件下的售后数据
        List<XlCustomerAftersale> list = aftersaleService.list(Wrappers.query(XlCustomerAftersale.class)
            .between(query.getOrderDate_start() != null && query.getOrderDate_end() != null,"DATE(create_time)", query.getOrderDate_start(), query.getOrderDate_end())
            .lambda().eq(StringUtils.isNotBlank(query.getStoreCode()),XlCustomerAftersale::getStoreCode, query.getStoreCode())
            .exists(StringUtils.isNotBlank(existsWhere),"select 1 from xl_customer_orde co where co.order_code = t2.order_code {0} ", existsWhere)
        );

        HomeAftersaleVO aftersaleVO = new HomeAftersaleVO(); // 售后数据信息
        aftersaleVO.setAftersaleSum(list.size());//售后订单数

        //订单总金额
        double sum = list.stream().mapToDouble(XlCustomerAftersale::getTotalAmount).sum();
        aftersaleVO.setSumAmount(sum);

        aftersaleVO.setRensonList(Lists.newArrayList());//初始化
        //处理售后订单原因占比
        Map<String, List<XlCustomerAftersale>> rensonMap = list.stream().filter(f-> f.getRenson() != null).collect(Collectors.groupingBy(XlCustomerAftersale::getRenson));

        //售后原因列表
        List<DictModel> rensonList = dictUtils.getDictMapByCode("slt_aftersale_renson");
        BigDecimal sizeSum = BigDecimal.ZERO; //累计占比
        int x = 0; //上一个原因有值的下标
        for (int i = 0; i < rensonList.size() && rensonMap.size() > 0; i++) {
            String s = rensonList.get(i).getValue();
            //原因占比率
            BigDecimal scale = BigDecimal.ZERO;
            if (rensonMap.get(s) != null){
                //原因占比率   原因数/总数
                scale = new BigDecimal(rensonMap.get(s).size() / list.size() * 100).setScale(2);
                x = i;
            }

            //避免精度问题 最后一个直接取余数
            if (i == rensonList.size()-1 ){
                if (rensonMap.get(s) != null){
                    scale = new BigDecimal(100).subtract(sizeSum).setScale(2);
                }else {
                    //如果最后一个 字典没有值 则给上一个有
                    BigDecimal decimal = new BigDecimal(100).subtract(sizeSum).setScale(2);
                    aftersaleVO.getRensonList().get(x).setValue(decimal);
                }
            } else {
                sizeSum.add(scale);
            }
            aftersaleVO.getRensonList().add(new HomeAftersaleRensonVO(rensonList.get(i).getTitle(),scale));
        }

        aftersaleVO.setTypeList(homeMapper.getAftersaleTypeList(query)); //售后种类列表统计
        aftersaleVO.setList(homeMapper.getAftersaleList(query)); //商品售后列表

        //写入字典标题
        for (HomeAftersaleTypeListVO listVO : aftersaleVO.getTypeList()) {
            listVO.setAftersaleType(dictUtils.getDictTitle("slt_aftersale_type",listVO.getAftersaleType()));
        }
        for (HomeAftersaleListVO listVO : aftersaleVO.getList()) {
            listVO.setRenson(dictUtils.getDictTitle("slt_aftersale_renson",listVO.getRenson()));
        }
        return aftersaleVO;
    }

    @Override
    public HomeDataVO queryOrderData(HomeQuery query) {
        return homeMapper.queryOrderData(query);
    }
}
